from zope.interface import Interface
from zope.interface import implements
from Acquisition import aq_inner
from plone.memoize.instance import memoize
from Products.CMFCore.utils import getToolByName
from zope.component import getMultiAdapter

from plone.app.portlets.portlets import base
from plone.portlets.interfaces import IPortletDataProvider
from plone.app.vocabularies.catalog import SearchableTextSourceBinder
from plone.app.form.widgets.uberselectionwidget import UberSelectionWidget

from zope import schema
from zope.formlib import form
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from my315ok.xtinfocontent.interfaces.ad import Iad ,IadMark

from my315ok.xtinfocontent import xtinfocontentMessageFactory as _

class Iadportlet(IPortletDataProvider):
    """A portlet

    It inherits from IPortletDataProvider because for this portlet, the
    data that is being rendered and the portlet assignment itself are the
    same.
    """

    # TODO: Add any zope.schema fields here to capture portlet configuration
    # information. Alternatively, if there are no settings, leave this as an
    # empty interface - see also notes around the add form and edit form
    # below.

    # some_field = schema.TextLine(title=_(u"Some field"),
    #                              description=_(u"A field to use"),
    #                              required=True)
    name = schema.TextLine(
           title=_(u"ad_title", default=u"Title"),
           description=_(u"help_title",
                         default=u"ad portlet title"),
           default=u"",
           required=False)
    
#    position = schema.Tuple(title=_(u"Ad position"),
#           description=_(u"select the Ad Position"),
#           default=('tl', ),
#           required=True,
#           value_type=schema.Choice(
#                                    vocabulary="my315ok.xtinfocontent.adposition")
#           )
    isflash = schema.Bool(title=_(u"display swf"),
                       description=_(u"If enabled, the portlet  will display swf flash."),
                       required=True,
                       default=True)
       
    target = schema.Choice(title=_(u"Target flash"),
                                  description=_(u"Find the flash file which provides the flash source"),
                                
                                  source=SearchableTextSourceBinder({'object_provides' : IadMark.__identifier__},
                                                                    default_query='path:'))


    
    width = schema.Int(title=_(u"width"),
                       description=_(u"Specify the width of the full ad."),
                       required=True)
    height = schema.Int(title=_(u"height"),
                       description=_(u"Specify the height of the full ad."),
                       required=True)
    state = schema.Tuple(title=_(u"Workflow state"),
           description=_(u"Items in which workflow state to show."),
           default=('published', ),
           required=True,
           value_type=schema.Choice(
                                    vocabulary="plone.app.vocabularies.WorkflowStates")
           )

        

    
class Assignment(base.Assignment):
    implements(Iadportlet)
    def __init__(self,name=u"",width=None,height=None,isflash=True,target=None,state=('published', )):
        
        self.state = state
        self.name= name
        self.isflash = isflash
        self.width = width
        self.height = height
        self.target = target

    title = _(u'Ads', default=u'Ads')


class Renderer(base.Renderer):

    def __init__(self, context, request, view, manager, data):
        base.Renderer.__init__(self, context, request, view, manager, data)
       
    def title(self):
        return self.data.name or ''      
        
    def update(self):
        pass
    
    def isflash(self):
        if self.data.isflash:
            return True
        else:
            return False
        
    @memoize
    def fetch_target(self):
        """ get the ad object"""
        
#        import pdb
#        pdb.set_trace()

        target_path = self.data.target
        context = aq_inner(self.context)
     
        if not target_path:
            return None
        if target_path.startswith('/'):
            target_path = target_path[1:]           
        portal_state = getMultiAdapter((context, self.request), name=u'plone_portal_state')
#        swf_url = portal_state.portal_url() + target_path
        portal = portal_state.portal()
        return portal.unrestrictedTraverse(target_path, default=None)
#        swfrender = swf_url + "/index_html"
#        return swfrender

    def swfurl(self):
        obj = self.getFilteredBanners()
        url = obj.absolute_url() + "/index_html"
        return  url
    def imgurl (self):
        obj = self.getFilteredBanners()
        url = obj.absolute_url() + "/at_download/image"
        return  url
    def width(self):
        return self.data.width
    def height(self):
        return self.data.height
    def geturl(self):
        obj = self.getFilteredBanners()
        outurl = obj.getLinkextern()
        if outurl == '':
            url = obj.getLinkintern()
            
        else:
            url = outurl            
       
        return  url
        
    def swfclickablecss(self):
#        import pdb
#        pdb.set_trace()
        s = """width:%s;height:%s;background:transparent;border:0;padding:0;cursor:pointer""" % (self.width(),self.height()) 
        
        return s 
    def swfclickable(self):
        s = """window.location.href='%s'""" %  self.geturl()
        return s
        
        
    @memoize 
    def getFilteredBanners(self):
        return self.fetch_target()

    render = ViewPageTemplateFile('adportlet.pt')
    


# NOTE: If this portlet does not have any configurable parameters, you can
# inherit from NullAddForm and remove the form_fields variable.

class AddForm(base.AddForm):
    """Portlet add form.

    This is registered in configure.zcml. The form_fields variable tells
    zope.formlib which fields to display. The create() method actually
    constructs the assignment that is being added.
    """
    form_fields = form.Fields(Iadportlet)
    form_fields['target'].custom_widget = UberSelectionWidget

    def create(self, data):
        return Assignment(**data)


# NOTE: IF this portlet does not have any configurable parameters, you can
# remove this class definition and delete the editview attribute from the
# <plone:portlet /> registration in configure.zcml

class EditForm(base.EditForm):
    """Portlet edit form.

    This is registered with configure.zcml. The form_fields variable tells
    zope.formlib which fields to display.
    """
    form_fields = form.Fields(Iadportlet)
    form_fields['target'].custom_widget = UberSelectionWidget
